<?php

declare(strict_types=1);

namespace app\shop\controller\admin\goods;

use think\Request;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\shop\model\goods\Service as ServiceModel;

/**
 * 服务保障
 */
class Service extends Backend
{
    
    public function initialize()
    {
        $this->model = new ServiceModel;
    }


    /**
     * 服务保障列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $services = $this->model->sheepFilter()->paginate(request()->param('list_rows', 10));

        return success('获取成功', $services);
    }




    /**
     * 添加服务保障
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $params = $this->request->only([
            'name', 'image', 'description'
        ]);
        $this->svalidate($params, ".add");

        Db::transaction(function () use ($params) {
            $this->model->save($params);
        });
        return success('保存成功');
    }


    /**
     * 服务保障详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $service = $this->model->findOrFail($id);

        return success('获取成功', $service);
    }



    /**
     * 修改服务保障
     *
     * @return \think\Response
     */
    public function edit($id)
    {
        $params = $this->request->only([
            'name', 'image', 'description'
        ]);
        $this->svalidate($params, ".edit");

        $id = explode(',', $id);
        Db::transaction(function () use ($id, $params) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $service) {
                $service->save($params);
            }
        });
        return success('更新成功');
    }



    /**
     * 删除服务标签
     *
     * @param string $id 要删除的服务保障列表
     * @return void
     */
    public function delete($id)
    {
        $id = explode(',', $id);

        Db::transaction(function () use ($id) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $service) {
                $service->delete();
            }
        });

        return success('删除成功');
    }


    /**
     * 获取所有服务列表
     *
     * @return \think\Response
     */
    public function select()
    {
        $services = $this->model->field('id, name')->select();

        return success('获取成功', $services);
    }
}
